package com.cml.sqlversionupgradestarter.service;

import cn.hutool.core.date.DateTime;
import com.cml.sqlversionupgradestarter.context.SQLVersionUpgradeContext;
import com.cml.sqlversionupgradestarter.entity.SqlUpgradeIndex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 作者：陈茂林
 * 时间：2022/1/6
 * 描述：解析sql版本升级索引文件
 */
public class SqlVersionIndexSqlExpression implements SqlExpression {
    private Logger logger= LoggerFactory.getLogger(SqlVersionIndexSqlExpression.class);
    private File file;

    private SQLVersionUpgradeContext sqlVersionUpgradeContext;
    public SqlVersionIndexSqlExpression(SQLVersionUpgradeContext sqlVersionUpgradeContext,File file){
        this.file = file;
        this.sqlVersionUpgradeContext = sqlVersionUpgradeContext;
    }
    @Override
    public void interpret() {
        String fileName = file.getName();
        FileInputStream fileInputStream= null;
        try {
            fileInputStream = new FileInputStream(this.file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));

            while (true){
                String temp = reader.readLine();
                if(temp != null){
                    if(temp.startsWith("--")){//注释
                        String[] lineSplit = temp.split(" ");
                        SqlUpgradeIndex sqlUpgradeIndex= new SqlUpgradeIndex();

                        if(lineSplit.length == 3){
                            sqlUpgradeIndex.setSqlUpgradeVersionFileName(lineSplit[1]);
                            sqlUpgradeIndex.setDate(new DateTime(lineSplit[2],"yyyyMMdd"));
                        }else{
                            throw new RuntimeException(temp +"格式不正确！");
                        }

                        sqlVersionUpgradeContext.getSqlUpgradeContext().addSqlUpgradeIndex(sqlUpgradeIndex);
                    }
                }else{
                    break;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
}
